<template>
  <view class="task-start-page">
    <!-- 导航栏 -->
    <u-navbar title="开始任务" back-icon="arrow-left" />
    
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-state">
      <u-loading-icon mode="circle" size="28" color="#409EFF"></u-loading-icon>
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 任务信息 -->
    <view v-else-if="taskInfo" class="task-content">
      <!-- 任务基本信息 -->
      <view class="task-card">
        <view class="card-header">
          <text class="task-title">{{ taskInfo.taskName }}</text>
          <u-tag 
            :text="getTaskTypeText(taskInfo.taskType)" 
            :type="getTaskTypeTagType(taskInfo.taskType)"
            size="small"
          />
        </view>
        
        <view class="card-content">
          <view class="info-item">
            <u-icon name="location" size="16" color="#666"></u-icon>
            <text class="info-text">{{ taskInfo.areaName || '未知区域' }}</text>
          </view>
          <view class="info-item">
            <u-icon name="clock" size="16" color="#666"></u-icon>
            <text class="info-text">{{ formatDateTime(taskInfo.scheduledDate, taskInfo.scheduledTime) }}</text>
          </view>
          <view class="info-item">
            <u-icon name="user" size="16" color="#666"></u-icon>
            <text class="info-text">{{ taskInfo.assignedUserName || '未分配' }}</text>
          </view>
          <view class="info-item" v-if="taskInfo.description">
            <u-icon name="file-text" size="16" color="#666"></u-icon>
            <text class="info-text">{{ taskInfo.description }}</text>
          </view>
        </view>
      </view>
      
      <!-- 执行记录表单 -->
      <view class="execution-form">
        <view class="form-title">
          <u-icon name="edit" size="18" color="#333"></u-icon>
          <text class="title-text">执行记录</text>
        </view>
        
        <u-form :model="formData" ref="formRef" :rules="rules">
          <!-- 清洁前照片 -->
          <view class="form-item">
            <AppImageUpload
              v-model="formData.beforePhotos"
              title="清洁前照片"
              tip="建议拍摄清洁前的状态照片，用于对比"
              :max-count="3"
              :required="false"
              add-button-text="添加照片"
              :max-size="5"
              :multiple="true"
              :allow-camera="true"
              :allow-album="true"
              :auto-upload="true"
              upload-type="CLEANING_IMAGE"
              upload-source="APP"
              @success="handleImageUploadSuccess"
              @error="handleImageUploadError"
            />
          </view>
          
          <!-- 使用工具 -->
          <view class="form-item">
            <view class="form-label">使用工具</view>
            <u-input 
              v-model="formData.toolsUsed" 
              placeholder="请输入使用的清洁工具"
              maxlength="200"
              class="form-input"
            />
          </view>
          
          <!-- 备注信息 -->
          <view class="form-item">
            <view class="form-label">备注信息</view>
            <u-textarea 
              v-model="formData.remark" 
              placeholder="请输入备注信息"
              maxlength="500"
              :auto-height="true"
              class="form-textarea"
            />
          </view>
        </u-form>
      </view>
      
      <!-- 操作按钮 -->
      <view class="action-section">
        <u-button 
          type="primary" 
          text="开始执行"
          size="large"
          :loading="submitting"
          @click="startTask"
          class="action-btn"
        />
        <u-button 
          type="default" 
          text="取消"
          size="large"
          @click="goBack"
          class="action-btn"
        />
      </view>
    </view>
    
    <!-- 空状态 -->
    <view v-else class="empty-state">
      <u-icon name="info-circle" size="48" color="#ccc"></u-icon>
      <text class="empty-text">任务信息不存在</text>
    </view>
  </view>
</template>

<script setup>
/**
 * 保洁任务开始执行页面
 * 严格按照《App端编码规范权威标准声明.md》规范实现
 * 用于保洁人员开始执行保洁任务
 * 
 * @author Wu.Liang
 * @date 2025-01-30
 */

import { ref, reactive, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getCleaningTaskDetailInfo, startCleaningTask } from '@/api/cleaning'
import AppImageUpload from '@/components/AppImageUpload.vue'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const taskInfo = ref(null)
const taskId = ref(null)

// 表单数据
const formData = reactive({
  beforePhotos: [],
  toolsUsed: '',
  remark: ''
})

// 表单验证规则
const rules = {
  // 任务开始阶段不需要强制验证照片
}

// 表单引用
const formRef = ref(null)

// 任务类型映射
const taskTypeMap = {
  'routine': '常规',
  'temporary': '临时',
  'special': '特殊'
}

// 任务类型标签类型映射
const taskTypeTagMap = {
  'routine': 'primary',
  'temporary': 'warning',
  'special': 'error'
}

/**
 * 获取任务类型文本
 */
const getTaskTypeText = (type) => {
  return taskTypeMap[type] || '未知'
}

/**
 * 获取任务类型标签类型
 */
const getTaskTypeTagType = (type) => {
  return taskTypeTagMap[type] || 'default'
}

/**
 * 格式化日期时间
 */
const formatDateTime = (date, time) => {
  if (!date) return ''
  const dateStr = new Date(date).toLocaleDateString('zh-CN')
  return time ? `${dateStr} ${time}` : dateStr
}

/**
 * 获取状态文本
 */
const getStatusText = (status) => {
  const statusMap = {
    1: '待分配',
    2: '已分配',
    3: '进行中',
    4: '已完成',
    5: '已取消'
  }
  return statusMap[status] || '未知状态'
}


/**
 * 加载任务详情
 */
const loadTaskDetail = async () => {
  if (!taskId.value) {
    console.error('任务ID为空，无法加载任务详情')
    return
  }
  
  console.log('开始加载任务详情，任务ID:', taskId.value)
  loading.value = true
  
  try {
    const response = await getCleaningTaskDetailInfo(taskId.value)
    console.log('任务详情API响应:', response)
    
    if (response && response.success && response.data) {
      taskInfo.value = response.data
      console.log('任务信息加载成功:', taskInfo.value)
      
      // 检查任务状态，确保可以开始执行
      // 状态2表示"已分配"，可以开始执行
      if (taskInfo.value.status !== 2) {
        uni.showToast({
          title: `任务状态不正确，当前状态：${getStatusText(taskInfo.value.status)}，无法开始执行`,
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 2000)
        return
      }
    } else {
      console.error('任务详情加载失败:', response)
      uni.showToast({
        title: response?.message || '任务不存在或已被删除',
        icon: 'none'
      })
      // 延迟返回上一页
      setTimeout(() => {
        uni.navigateBack()
      }, 2000)
    }
  } catch (error) {
    console.error('加载任务详情失败:', error)
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none'
    })
    // 延迟返回上一页
    setTimeout(() => {
      uni.navigateBack()
    }, 2000)
  } finally {
    loading.value = false
  }
}

/**
 * 图片上传成功处理
 */
const handleImageUploadSuccess = (images) => {
  console.log('清洁前照片上传成功:', images)
  uni.showToast({
    title: '照片上传成功',
    icon: 'success'
  })
}

/**
 * 图片上传失败处理
 */
const handleImageUploadError = (error) => {
  console.error('清洁前照片上传失败:', error)
  uni.showToast({
    title: '照片上传失败',
    icon: 'none'
  })
}

/**
 * 开始执行任务
 */
const startTask = async () => {
  try {
    submitting.value = true
    
    // 处理图片数据 - 参考报修服务页面的实现方式
    // 后端期望beforePhotos字段，包含图片URL列表
    const processedBeforePhotos = formData.beforePhotos.map(image => {
      // 提取图片URL，支持多种格式
      const imageUrl = image.url || image.fileUrl || image
      console.log('提取图片URL:', imageUrl, 'from image:', image)
      return imageUrl
    }).filter(Boolean) // 过滤掉空值
    
    const submitData = {
      taskId: taskId.value,
      beforePhotos: processedBeforePhotos,
      toolsUsed: formData.toolsUsed,
      remark: formData.remark
    }
    
    const response = await startCleaningTask(submitData)
    if (response.success) {
      uni.showToast({
        title: '任务开始执行成功',
        icon: 'success'
      })
      
      // 延迟跳转到任务管理列表页面
      setTimeout(() => {
        uni.redirectTo({
          url: '/pages/property-work/cleaning-management/task-management',
          success: () => {
            console.log('跳转到任务管理列表页面成功')
          },
          fail: (err) => {
            console.error('跳转到任务管理列表页面失败:', err)
            // 如果跳转失败，则返回上一页
            uni.navigateBack()
          }
        })
      }, 1500)
    } else {
      uni.showToast({
        title: response.message || '开始执行失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('开始执行任务失败:', error)
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none'
    })
  } finally {
    submitting.value = false
  }
}

/**
 * 返回上一页
 */
const goBack = () => {
  uni.navigateBack()
}

/**
 * 页面加载时获取参数
 */
onLoad((options) => {
  console.log('onLoad获取参数:', options)
  console.log('参数类型:', typeof options)
  console.log('参数内容:', JSON.stringify(options))
  
  if (options && options.id) {
    console.log('原始ID值:', options.id, '类型:', typeof options.id)
    const id = parseInt(options.id)
    console.log('解析后的ID值:', id, '是否有效:', !isNaN(id) && id > 0)
    
    if (!isNaN(id) && id > 0) {
      taskId.value = id
      console.log('onLoad设置任务ID成功:', taskId.value)
      loadTaskDetail()
      return
    } else {
      console.error('任务ID无效:', options.id)
    }
  } else {
    console.error('未获取到ID参数:', options)
  }
  
  // 如果onLoad没有获取到有效参数，显示错误并返回
  console.error('缺少任务ID参数')
  uni.showToast({
    title: '缺少任务ID参数',
    icon: 'none'
  })
  setTimeout(() => {
    uni.navigateBack()
  }, 1500)
})

/**
 * 页面加载时初始化
 */
onMounted(() => {
  // onLoad已经处理了参数获取，这里不需要额外处理
  console.log('页面初始化完成，任务ID:', taskId.value)
})
</script>

<style lang="scss" scoped>
.task-start-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #f5f5f5;
}

.loading-text {
  margin-top: 12px;
  font-size: 14px;
  color: #666;
}

.task-content {
  flex: 1;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.task-card {
  background-color: #fff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.task-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  flex: 1;
  margin-right: 12px;
}

.card-content {
  .info-item {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .info-text {
      font-size: 14px;
      color: #666;
      margin-left: 8px;
      flex: 1;
    }
  }
}

.execution-form {
  background-color: #fff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.form-title {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.title-text {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-left: 8px;
}

.form-item {
  margin-bottom: 20px;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  display: block;
}

.form-input {
  width: 100%;
}

.form-textarea {
  width: 100%;
}


.action-section {
  padding: 20px 0;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.action-btn {
  width: 100%;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #f5f5f5;
}

.empty-text {
  font-size: 14px;
  color: #999;
  margin-top: 12px;
}

/* 响应式适配 */
@media screen and (max-width: 375px) {
  .task-content {
    padding: 12px;
  }
  
  .task-card,
  .execution-form {
    padding: 16px;
  }
}
</style>
